package com.tsmti.task.service.impl;


import com.tsmti.core.common.constant.Constants;
import com.tsmti.core.common.service.impl.BaseServiceImpl;
import com.tsmti.core.quartz.QuartzManager;
import com.tsmti.task.entity.ScheduleJob;
import com.tsmti.task.service.ScheduleJobService;
import com.tsmti.task.utils.ScheduleJobUtils;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * @Package：com.tsmti.task.service.impl
 * @Class：ScheduleJobServiceImpl
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/5/15 22:39
 * @Company:
 * @Version：
 * @Modified By:
 */
@Transactional(rollbackFor = Exception.class)
@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends BaseServiceImpl<ScheduleJob> implements ScheduleJobService {
    private QuartzManager quartzManager;

    @Override
    public void updateCron(String jobId) throws SchedulerException {
        ScheduleJob scheduleJobEntity = get(jobId);
        if (scheduleJobEntity == null) {
            return;
        }
        if (com.tsmti.core.quartz.data.ScheduleJob.STATUS_RUNNING.equals(scheduleJobEntity.getJobStatus())) {
            quartzManager.updateJobCron(ScheduleJobUtils.entityToData(scheduleJobEntity));
        }
        update(scheduleJobEntity);
    }

    @Override
    public void changeStatus(String jobId, String cmd) throws SchedulerException {
        ScheduleJob scheduleJobEntity = get(jobId);
        if (scheduleJobEntity == null) {
            return;
        }
        if (Constants.STOP.equals(cmd)) {
            quartzManager.deleteJob(ScheduleJobUtils.entityToData(scheduleJobEntity));
            scheduleJobEntity.setJobStatus(com.tsmti.core.quartz.data.ScheduleJob.STATUS_NOT_RUNNING);
        } else if (Constants.START.equals(cmd)) {
            scheduleJobEntity.setJobStatus(com.tsmti.core.quartz.data.ScheduleJob.STATUS_RUNNING);
            quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJobEntity));
        }
        update(scheduleJobEntity);
    }

    @Override
    public void remove(ScheduleJob entity) {
        try {
            quartzManager.deleteJob(ScheduleJobUtils.entityToData(entity));
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        super.remove(entity);
    }

    @Override
    public void removeById(Serializable id) {
        remove(get(id));
    }

    @Override
    public void initSchedule() throws SchedulerException {
        // 这里获取任务信息数据
        quartzManager = new QuartzManager();
        List<ScheduleJob> jobList = list();
        for (ScheduleJob scheduleJobEntity : jobList) {
            quartzManager.addJob(ScheduleJobUtils.entityToData(scheduleJobEntity));
        }
    }

}
